import uid from './uid'

const store = chrome.storage.local
export function getCurrentTab(): Promise<chrome.tabs.Tab> {
  return new Promise((resolve, reject) => {
    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
      if (tabs.length) {
        const [firstTab] = tabs
        resolve(firstTab)
      } else {
        reject()
      }
    })
  })
}

export function setState<T>(items: T) {
  return new Promise<boolean>((resolve, reject) => {
    try {
      store.set(items, () => {
        resolve(true)
      })
    } catch (error) {
      reject(error)
    }
  })
}

export function getState<T>(key?: string | null) {
  return new Promise<T>((resolve, reject) => {
    try {
      store.get(key || null, obj => {
        resolve(key ? obj[key] : obj)
      })
    } catch (error) {
      reject(error)
    }
  })
}

export function uuid(): string {
  return uid()
}
